#include "client.h"

void* readMessage(void *fd);
client* client::s_inst = 0;
client::client():
    s(-1)
{

}

client *client::inst()
{
    if(s_inst == 0)
    {
        s_inst = new client();
    }
    return s_inst;
}

void client::registClient()
{
    sockaddr_in server_addr;
    int err;
    /********************socket()*********************/
    s= socket(AF_INET,SOCK_STREAM,0);
    if(s<0)
    {
        printf("client : create socket error\n");
        return;
    }

    /*******************connect()*********************/
    //设置服务器地址结构，准备连接到服务器
    memset(&server_addr,0,sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_addr.s_addr = inet_addr(SERVERIP);

    err = connect(s,(struct sockaddr *)&server_addr,sizeof(sockaddr));
    if(err == 0)
    {
        printf("client : connect to server\n");
    }
    else
    {
        printf("client : connect error\n");
        return;
    }
    pthread_t pid;
    pthread_create(&pid,NULL,readMessage,&s);
    //与服务器端进行通信
    handle();
    close(s);
}

int client::closeClient()
{
    int ret = close(s);
    return ret;
}

void client::handle()
{
    ssize_t size = 0;
    data d;

    while(1)
    {
        memset(&d,0,sizeof(data));
        /*从标准输入中读取数据放到缓冲区buffer中*/
        d.cmd = CMD_SENDMESSAGE;
        d.sender = s;
        d.receiver = s;
        cout<<"please input: "<<endl;
        cin>>d.buf;
        write(s,&d,sizeof(data));
        //        if(size >  0)
        //        {
        //            //当向服务器发送 “quit” 命令时，服务器首先断开连接
        //            write(s,buffer,strlen(buffer)+1);   //向服务器端写

        //            //等待读取到数据
        //            for(size = 0 ; size == 0 ; size = read(s,buffer,Buflen) );

        //            write(1,buffer,strlen(buffer)+1);   //向标准输出写
        //        }
    }
}

void *readMessage(void *fd)
{
    int new_fd = *(int*)fd;
    ssize_t read_bytes;
    client::data r_buf;
    memset(&r_buf,0,sizeof(r_buf));
    while(1)
    {
        for(read_bytes = 0; read_bytes == 0; read_bytes = read(new_fd,&r_buf,sizeof(r_buf)))
        {
            cout<<r_buf.buf<<endl;
        }
    }
}
